package com.bestcem.xm.member.grpc.client;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bestcem.bp.grpc.v1.base.Page;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.label.constant.Constants;
import com.bestcem.xm.member.service.dto.AuthorizedOrgInfoDTO;
import com.bestcem.xm.member.service.dto.WechatOfficialAccountInfoDTO;
import com.bestcem.xm.member.service.dto.WechatOpenIdDTO;
import com.bestcem.xm.member.service.dto.WechatUserBasicInfoDTO;
import com.bestcem.xm.push.grpc.v1.services.*;
import io.grpc.StatusRuntimeException;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 示例服务
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2022/3/29
 */
@Slf4j
@Component("pushClient")
public class PushClient {

    @GrpcClient(GrpcClientNames.DS_PUSH)
    private WechatOfficialAccountServiceGrpc.WechatOfficialAccountServiceBlockingStub stub;

    public ServiceResult<List<WechatOfficialAccountInfoDTO>> listAccountInfo(String orgId) {
        if (StrUtil.isEmpty(orgId)) {
            return ServiceResult.fail("orgId 不能为空");
        }

        ListAccountInfoRequest.Builder builder = ListAccountInfoRequest.newBuilder();
        builder.setOrgId(orgId);
        ListAccountInfoResponse response = null;

        try {
            response = stub.listAccountInfo(builder.build());
            if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
                log.error("【Member】根据组织id {} 获取授权的公众号信息, response: {}", orgId, response);
                return ServiceResult.fail("获取数据失败");
            }
        } catch (StatusRuntimeException e) {
            String msg = String.format("【Member】根据组织id {} 获取授权的公众号信息, %s", builder.toString());
            log.error(msg, e);
            return ServiceResult.fail(msg);
        }

        List<WechatOfficialAccountInfo> infoList = response.getInfoList();
        if (CollUtil.isNotEmpty(infoList)) {
            List<WechatOfficialAccountInfoDTO> dtos = infoList.stream().map(item -> {
                WechatOfficialAccountInfoDTO dto = new WechatOfficialAccountInfoDTO();
                dto.setAppId(item.getAppId());
                dto.setAuthorizeTime(DateUtil.getDate(item.getAuthorizeTime()));
                dto.setAvatarUrl(item.getAvatarUrl());
                dto.setNickname(item.getNickname());
                dto.setVersion(item.getVersion());
                return dto;
            }).collect(Collectors.toList());
            return ServiceResult.success(dtos);
        }
        return ServiceResult.success();
    }

    public ServiceResult<WechatOpenIdDTO> listOpenIds(String orgId, String appId, Integer version, String nextOpenId) {

        if (StrUtil.isEmpty(orgId)) {
            return ServiceResult.fail("orgId 不能为空");
        }

        if (StrUtil.isEmpty(appId)) {
            return ServiceResult.fail("appId 不能为空");
        }

        if (ObjectUtil.isEmpty(version)) {
            return ServiceResult.fail("version 不能为空");
        }

        ListOpenIdsRequest.Builder builder = ListOpenIdsRequest.newBuilder();
        builder.setAppId(appId);
        builder.setOrgId(orgId);
        builder.setVersion(version);

        if (StrUtil.isNotEmpty(nextOpenId)) {
            builder.setNextOpenId(nextOpenId);
        }

        ListOpenIdsResponse response = null;
        try {
            response = stub.listOpenIds(builder.build());
            if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
                log.error("【Member】获取微信公众号用户openId列表失败, response: {}", response);
                return ServiceResult.fail("获取数据失败");
            }
        } catch (StatusRuntimeException e) {
            String msg = String.format("【Member】获取微信公众号用户openId列表失败, %s", builder.toString());
            log.error(msg, e);
            return ServiceResult.fail(msg);
        }

        WechatOpenIdDTO dto = new WechatOpenIdDTO();
        dto.setNextOpenId(response.getNextOpenId());
        dto.setOpenIds(response.getIdsList());
        return ServiceResult.success(dto);
    }

    public ServiceResult<List<WechatUserBasicInfoDTO>> listUserBasicInfo(List<String> openIds, String appId) {
        ListUserBasicInfoRequest.Builder builder = ListUserBasicInfoRequest.newBuilder();
        builder.setAppId(appId);
        builder.addAllOpenIds(openIds);
        ListUserBasicInfoResponse response = null;
        try {
            response = stub.listUserBasicInfo(builder.build());
            if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
                log.error("【Member】批量获取微信公众号用户基本信息, response: {}", response);
                return ServiceResult.fail("获取数据失败");
            }
        } catch (StatusRuntimeException e) {
            String msg = String.format("【Member】批量获取微信公众号用户基本信息, %s", builder.toString());
            log.error(msg, e);
            return ServiceResult.fail(msg);
        }

        List<UserBasicInfo> infoList = response.getInfoList();
        if (CollUtil.isNotEmpty(infoList)) {
            List<WechatUserBasicInfoDTO> dtos = infoList.stream().map(item -> {
                WechatUserBasicInfoDTO dto = new WechatUserBasicInfoDTO();
                dto.setOpenId(item.getOpenId());
                dto.setUnionId(item.getUnionId());
                dto.setAppId(appId);
                return dto;
            }).collect(Collectors.toList());
            return ServiceResult.success(dtos);
        }
        return ServiceResult.success();
    }

    public ServiceResult<List<AuthorizedOrgInfoDTO>> listAuthorizedOrgInfo(int page, int size) {
        ListAuthorizedOrgInfoRequest.Builder builder = ListAuthorizedOrgInfoRequest.newBuilder();
        Page.Builder pageBuild = Page.newBuilder();
        pageBuild.setSize(size);
        pageBuild.setPage(page);
        builder.setPage(pageBuild.build());
        ListAuthorizedOrgInfoResponse response = null;
        try {
            response = stub.listAuthorizedOrgInfo(builder.build());
            if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
                log.error("【Member】获取已授权公众号的租户信息列表, response: {}", response);
                return ServiceResult.fail("获取数据失败");
            }
        } catch (StatusRuntimeException e) {
            String msg = String.format("【Member】获取已授权公众号的租户信息列表, %s", builder.toString());
            log.error(msg, e);
            return ServiceResult.fail(msg);
        }
        List<AuthorizedOrgInfo> infoList = response.getInfoList();
        if (CollUtil.isNotEmpty(infoList)) {
            List<AuthorizedOrgInfoDTO> dtos = infoList.stream().map(item -> {
                AuthorizedOrgInfoDTO dto = new AuthorizedOrgInfoDTO();
                dto.setAppId(item.getAppId());
                dto.setId(item.getId());
                dto.setVersion(item.getVersion());
                return dto;
            }).collect(Collectors.toList());
            return ServiceResult.success(dtos);
        }
        return ServiceResult.success();

    }
}
